package com.irssproject.app.web.action.lectorRSS;

import com.irssproject.app.entitats.Feed;
import com.irssproject.app.entitats.Subscription;
import com.irssproject.app.entitats.Topic;
import com.irssproject.app.entitats.User;
import com.irssproject.app.entitats.recommendations.WebUser;
import com.irssproject.app.service.lectorRSS.iface.SubscriptionsService;
import com.irssproject.app.utils.Constants;
import com.irssproject.app.web.action.JSONWrappers.FeedJSON;
import com.irssproject.app.web.action.JSONWrappers.FeedsByTopic;
import com.irssproject.app.web.action.JSONWrappers.ItemsByTopic;
import com.irssproject.app.web.action.JSONWrappers.SubscriptionJSON;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sun.syndication.feed.synd.SyndFeed;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SubscriptionsAction extends ActionSupport {

    private static final long serialVersionUID = 1L;
    private String urlFeed;
    private String dataAvui;
    private SyndFeed feed;
    private String etiqueta;
    private String idSubscripcio;
    private String topic;
    private boolean fromRecommendation;
    private List<WebUser> usersSubscribedList;
    private List<Topic> topicsSubscribedList;
    private List<FeedsByTopic> feedsLst;
    private List<ItemsByTopic> itemsLst;

    public String getIdSubscripcio() {
        return idSubscripcio;
    }

    public void setIdSubscripcio(String idSubscripcio) {
        this.idSubscripcio = idSubscripcio;
    }
    private List<SubscriptionJSON> liSubscripcions;
    private List<String> liEtiquetes;
    Map<String, Object> session;
    private User usuari;
    private Feed feedIn;
    SubscriptionsService subscripcioService;
    Logger logger = Logger.getLogger(SubscriptionsAction.class.getName());

    public SubscriptionsAction(SubscriptionsService subscripcioService) {
        this.subscripcioService = subscripcioService;
    }
    private String errorMessage;

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }

    public String getDataAvui() {
        return dataAvui;
    }

    public void setDataAvui(String dataAvui) {
        this.dataAvui = dataAvui;
    }

    public void setUrlFeed(String urlFeed) {
        this.urlFeed = urlFeed;
    }

    public String getUrlFeed() {
        return urlFeed;
    }

    public void setFeed(SyndFeed feed) {
        this.feed = feed;
    }

    public SyndFeed getFeed() {
        return feed;
    }

    public void setLiEtiquetes(List<String> liEtiquetes) {
        this.liEtiquetes = liEtiquetes;
    }

    public List<String> getLiEtiquetes() {
        return liEtiquetes;
    }

    public void setEtiqueta(String etiqueta) {
        this.etiqueta = etiqueta;
    }

    public String getEtiqueta() {
        return etiqueta;
    }

    public void setLiSubscripcions(List<SubscriptionJSON> liSubscripcions) {
        this.liSubscripcions = liSubscripcions;
    }

    public List<SubscriptionJSON> getLiSubscripcions() {
        return liSubscripcions;
    }

    public boolean getFromRecommendation() {
        return fromRecommendation;
    }

    public void setFromRecommendation(boolean fromRecommendation) {
        this.fromRecommendation = fromRecommendation;
    }

    public List<WebUser> getUsersSubscribedList() {
        return usersSubscribedList;
    }

    public void setUsersSubscribedList(List<WebUser> usersSubscribedList) {
        this.usersSubscribedList = usersSubscribedList;
    }

    public List<Topic> getTopicsSubscribedList() {
        return topicsSubscribedList;
    }

    public void setTopicsSubscribedList(List<Topic> topicsSubscribedList) {
        this.topicsSubscribedList = topicsSubscribedList;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public List<FeedsByTopic> getFeedsLst() {
        return feedsLst;
    }

    public void setFeedsLst(List<FeedsByTopic> feedsLst) {
        this.feedsLst = feedsLst;
    }

    public List<ItemsByTopic> getItemsLst() {
        return itemsLst;
    }

    public void setItemsLst(List<ItemsByTopic> itemsLst) {
        this.itemsLst = itemsLst;
    }

    
    public String addNewSubscription() {

        try {
            session = ActionContext.getContext().getSession();
            User userSession = ((User) session.get(Constants.SESSIO_USUARI_AUTENTICAT));

            //get parameters from webpage and trim
            String feedURL = urlFeed.trim();
            String label = etiqueta != null && !etiqueta.isEmpty() ? etiqueta.trim() : null;

            subscripcioService.insertSubscription(userSession, feedURL, label, false);

        } catch (Exception e) {

            if (e.getMessage().equals(Constants.EXCEPTION_MALFORMED_FEED_URL)) {
                errorMessage = "The URL seems to be malformed";
            } else if (e.getMessage().equals(Constants.EXCEPTION_FEED_ALREADY_SUBSCRIBED)) {
                errorMessage = "You already have subscribed this feed. It won't be added.";
            } else {
                errorMessage = "There was an unexpected error. Try again.";
            }

            logger.log(Level.SEVERE, e.getMessage());

        }

        return SUCCESS;

    }

    public String eliminarSubscripcio() {

        try {
            session = ActionContext.getContext().getSession();
            usuari = ((User) session.get(Constants.SESSIO_USUARI_AUTENTICAT));

            subscripcioService.deleteSubscription(new Long(idSubscripcio));
        } catch (Exception e) {
            logger.severe(e.getMessage());
            errorMessage = "There are errors while removing subscription.";
        }

        return SUCCESS;

    }

    public String mostrarLlistaSubscripcions() {

        session = ActionContext.getContext().getSession();
        usuari = ((User) session.get(Constants.SESSIO_USUARI_AUTENTICAT));

        List<Subscription> llistaSubscripcions = subscripcioService.getSubscriptionsList(usuari, fromRecommendation);
        session.put(Constants.SESSIO_LLISTA_SUBSCRIPCIONS, llistaSubscripcions);

        List<SubscriptionJSON> liJSON = new ArrayList<SubscriptionJSON>();

        SubscriptionJSON sJSON;

        for (Subscription subs : llistaSubscripcions) {

            sJSON = new SubscriptionJSON();
            sJSON.setId(subs.getId());
            sJSON.setEtiqueta(subs.getLabel());
            sJSON.setFeed(new FeedJSON(subs.getFeed().getTitol(), subs.getFeed().getLink()));
            sJSON.setNumItemsNoLlegits(subs.getUnreadItemsNumber());
            liJSON.add(sJSON);
        }

        setLiSubscripcions(liJSON);

        return SUCCESS;
    }

    public String showUsersSubscribedList() {
        Map session = ActionContext.getContext().getSession();
        User connectedUser = ((User) session.get(Constants.SESSIO_USUARI_AUTENTICAT));

        List<User> userList = subscripcioService.getUsersSubscribed(connectedUser);
        usersSubscribedList = new ArrayList<WebUser>();
        for (User user : userList) {
            usersSubscribedList.add(new WebUser(user));
        }
        return SUCCESS;
    }

    public String showTopicsSubscribedList() {
        User connectedUser =((User) ActionContext.getContext().getSession().get(Constants.SESSIO_USUARI_AUTENTICAT));
        topicsSubscribedList = subscripcioService.getTopicsSubscribed(connectedUser);
        return SUCCESS;
    }

    public String getFeedLstByTopic() {
        if (topic != null && !topic.isEmpty()) {
            User connectedUser = ((User) ActionContext.getContext().getSession().get(Constants.SESSIO_USUARI_AUTENTICAT));
            System.out.println("Searching feeds by topic ---> " + topic);
            feedsLst = subscripcioService.getFeedsLstByTopic(connectedUser, topic);
        }
        return SUCCESS;
    }
    
    
    public String getItemsLstByTopic() {
        if (topic != null && !topic.isEmpty()) {
            User connectedUser = ((User) ActionContext.getContext().getSession().get(Constants.SESSIO_USUARI_AUTENTICAT));
            System.out.println("Searching items by topic ---> " + topic);
            itemsLst = subscripcioService.getItemsLstByTopic(connectedUser, topic);
        }
        return SUCCESS;
    }
}
